import Cigarettes from './cigarettes';
import SmokeMachine from './smokeMachine';
import tween from '../utils/tween';
import eventBus from '../utils/eventBus';
import { cigaretteList } from '../utils/config';


console.log(eventBus,'eventBus')

interface Options {
	canvas: WechatMiniprogram.Canvas;
	canvasWidth: number;
	canvasHeight: number;
	spriteSmokeImage: WechatMiniprogram.Image,
	cigaretteId: number;
	complete: (msg:string)=>void
}
class SmokingController implements Options{
	public canvas;
	public canvasWidth;
	public canvasHeight;
	public spriteSmokeImage;
	public cigaretteId;
	public complete;
	// public ashSpriteImage;
	public ctx: WechatMiniprogram.CanvasRenderingContext.CanvasRenderingContext2D;
	public cigarettes: any;
	public smokeMachine: any;
	public smokeMachineBottom: any;
	public running: boolean;
	public lastframe: number;
	public cigaretteConfig:any;
	public currentBodyH:number;
	public fps: number;
	public isBreatheIn: boolean;
	public isBreatheOutSmoking: boolean;
	public breatheOutSmokingAge: number;
	public burning: boolean;
	constructor(param: any) {
		const { canvas, width, height, spriteImageUrl, complete, cigaretteId } = param;
		const dpr = wx.getWindowInfo().pixelRatio
		this.canvas = canvas;
		this.canvas.width = width * dpr;
		this.canvas.height = height * dpr;
		this.canvasWidth = width;
		this.canvasHeight = height;
		this.complete = complete;
		this.ctx = this.canvas.getContext('2d');
		this.ctx.scale(dpr, dpr);
		//设置参数
		this.cigaretteId = cigaretteId || 1;
		this.cigaretteConfig = this.getCigaretteConfig();
		this.currentBodyH = this.cigaretteConfig.h - this.cigaretteConfig.filterH;
		this.spriteSmokeImage = canvas.createImage();
		this.spriteSmokeImage.src = spriteImageUrl;
		this.fps = 60;
		this.isBreatheIn = false;
		this.isBreatheOutSmoking = false;
		this.breatheOutSmokingAge = 0;
		this.burning = false;
		// this.ashSpriteImage = canvas.createImage();
		// this.ashSpriteImage.src = '/images/ash.png';
		this.lastframe = 0;//performance.now();
		this.running = false;
		const imagesPromise = [ this.spriteSmokeImage].map(item=>{
			return new Promise((resolve,reject)=>{
				item.onload = () => {
					resolve('success');
				}
			})
		})
		Promise.all(imagesPromise).then(res=>{
			// 将图片绘制到 canvas 上
			// this.ctx.drawImage(this.spriteSmokeImage, 100, 50);
			this.smokeMachine = new SmokeMachine({
				smokeParticleImage: this.spriteSmokeImage,
				context: this.ctx
			})
			this.smokeMachineBottom = new SmokeMachine({
				smokeParticleImage: this.spriteSmokeImage,
				context: this.ctx
			})
			this.cigarettes = new Cigarettes({ 
				canvasWidth: this.canvasWidth, 
				canvasHeight: this.canvasHeight,
				ctx: this.ctx,
				cigaretteConfig: this.cigaretteConfig
			});
			console.log('执行');
			
			this.start();
			//this.render(0);
			// this.canvas.requestAnimationFrame(this.frame.bind(this));

			this.smokeMachine.setPreDrawCallback((dt:any)=>{
				// console.log('dfewfer');
				if(!this.burning){
					return
				}
				const { w, h, x, y, bodyH } = this.cigaretteConfig;
				this.smokeMachine.addParticles(x + w/2,  y + (bodyH - this.currentBodyH), 0.2,{
					minVx: 0.00001/100,
					maxVx: 0.00001/100,
					minScale: 5,
					maxScale: 5
				});
			})

			this.smokeMachineBottom.setPreDrawCallback((dt:any)=>{
				// console.log('dfewfer');
				if(this.isBreatheOutSmoking){
					this.breatheOutSmokingAge = this.breatheOutSmokingAge + dt;
					if(this.breatheOutSmokingAge<1200){
						this.smokeMachine.addParticles(this.cigaretteConfig.x + this.cigaretteConfig.w/2,  this.canvasHeight, .2,{
							minVx: 0.1/100,
							maxVx: 0.2/100,
							minScale: 0,
							maxScale: 10,
							// minVy: 0.5,
							// maxVy: 1,
						});
					}else{
						this.isBreatheOutSmoking = false;
						this.breatheOutSmokingAge = 0;
					}
					
				}
				
			})
		})
	}

	reset(){
		this.cigaretteConfig = this.getCigaretteConfig();
		this.currentBodyH = this.cigaretteConfig.h - this.cigaretteConfig.filterH;
		this.isBreatheIn = false;
		this.isBreatheOutSmoking = false;
		this.burning = false;
		this.breatheOutSmokingAge = 0;
		this.cigarettes.reset(this.cigaretteConfig);
		console.log('===reset===')
	}

	setCigaretteId(id){
		this.cigaretteId = id || 1;
		this.cigaretteConfig = this.getCigaretteConfig();
		this.reset();
	}

	getCigaretteConfig():any{
		let item:any = cigaretteList.find(v=>v.id == this.cigaretteId);
		if(!item)item = cigaretteList[0];
		console.log(item,'009')
		const ch = this.canvasHeight * item.spec.screenRatio;
		const cw = ch*item.spec.width/item.spec.height;
		const bottom = 200; //距离底部
		const cx = this.canvasWidth/2 - cw/2;
		const cy = this.canvasHeight - ( ch + bottom );
		const filterH =  ch*item.spec.filterH/item.spec.height;
		const filterY =  cy + ( ch - filterH );
		const ringH = ch*item.spec.ringH/item.spec.height;
		const ringToFilter = ch*item.spec.ringToFilter/item.spec.height;
		const ringY = filterY + (ringToFilter || 0);
		const bodyH = ch - filterH;
		const lifeTime = item.spec.lifeTime;
		return {
			w: cw,
			h: ch,
			x: cx,
			y: cy,
			bottom,
			filterH,
			filterY, 
			ringH,
			ringY,
			bodyH,
			lifeTime,
			ashRowCount: item.spec.ashRowCount,
			bounceStartSpeed: 0.4,
			bodyColor: item.spec.bodyColor,
			filterColor: item.spec.filterColor,
			ringColor: item.spec.ringColor
		}
	}

	start(){
		this.running = true;
		this.lastframe = Date.now();
		this.canvas.requestAnimationFrame(this.frame.bind(this));
	}

	light(){
		//点燃操作
		eventBus.emit('light',true);
		this.burning = true;
	}

	bounce(){
		eventBus.emit('bounce',true);
	}

	breath(type:string){
		this.isBreatheIn = type=='in'?true:false;
		if(type == 'out'){
			this.isBreatheOutSmoking = true;
		}
	}

	frame():void{
		const time = Date.now();
		let dt = time - this.lastframe;
		this.fps = 1000/dt;
		this.lastframe = time;
		this.render(dt);
		if(this.running)this.canvas.requestAnimationFrame(this.frame.bind(this));
	}

	async render(dt:number):Promise<void>{
		this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
		//计算燃烧后的高度
		const { w, h, x, y, bodyH, lifeTime } = this.cigaretteConfig;
		const frameFadeHeight = this.isBreatheIn?bodyH/( (lifeTime/1000)*60 ):0;//lifeTime*20;
		this.currentBodyH = this.currentBodyH - frameFadeHeight;
		if(this.currentBodyH<0){
			this.currentBodyH = 0;
			if(this.burning){
				this.complete('end');
				this.burning = false;
			}
			// this.running = false;
		}

		//渲染香烟
		this.cigarettes.draw(dt,this.currentBodyH);
		//渲染烟雾
		this.smokeMachine.updateAndDrawParticles(dt);
		this.smokeMachineBottom.updateAndDrawParticles(dt);
	}
}

export default SmokingController